/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.aipocr;

import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * AipOcr百度文字识别
 * https://ai.baidu.com/ai-doc/OCR/nk3h7yc12
 * @author duanlikao
 * @created 2020/11/28 upDocumentTypeConstant
 */
@Slf4j
@Service
public class AipOcrService {

    private static AipOcr aipOcrs ;


    private static final Logger LOGGER = LoggerFactory.getLogger(AipOcrService.class);

    /* 图像方向，当detect_direction=true时存在。
     *  -1:未定义，
     *  - 0:正向，
     *  - 1: 逆时针90度，
     *  - 2:逆时针180度，
     *  - 3:逆时针270度
     */
    private static  Integer direction;

    /**
     * normal-识别正常
     * reversed_side-身份证正反面颠倒
     * non_idcard-上传的图片中不包含身份证
     * blurred-身份证模糊
     * other_type_card-其他类型证照
     * over_exposure-身份证关键字段反光或过曝
     * unknown-未知状态
     */
    private static String image_status;

    /**
     * 识别结果数，表示words_result的元素个数
     */

    private static Integer words_result_num;

    /**
     * normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknow-其他未知情况
     */
    private static String risk_type;



    private AipOcrService(){
        AipFactory aipFactory  =  new AipFactory();
        aipOcrs = aipFactory.getAipOcr();
    }

    /**
     * 通用文字识别
     * @param file
     * @return
     */
    public  String basicGeneral (String file) {
        HashMap <String, String> options = new HashMap <>(4);
        options.put("language_type", "CHN_ENG");
        // 检测图片朝上
        options.put("detect_direction", "true");
        // 检测语言,默认是不检查
        options.put("detect_language", "true");
        //是否返回识别结果中每一行的置信度
        options.put("probability", "true");
//        LOGGER.info("AipOcrService | basicGeneral  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.basicGeneral(file, options);
//        LOGGER.info("AipOcrService | basicGeneral  result  jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }

    /**
     * 高精度通用文字识别
     * @param file
     * @return
     */
    public   String basicAccurateGeneral (String file) {
        HashMap<String,String> options = new HashMap<>(4);
        options.put("language_type", "CHN_ENG");
        // 检测图片朝上
        options.put("detect_direction", "true");
        // 检测语言,默认是不检查
        options.put("detect_language", "true");
        //是否返回识别结果中每一行的置信度
        options.put("probability", "true");
//        LOGGER.info("AipOcrService | basicAccurateGeneral  file:{} | options:{} ",file ,options);
        JSONObject jsonObject =  aipOcrs.basicAccurateGeneral(file, options);
//        LOGGER.info("AipOcrService | basicAccurateGeneral  result jsonObject:{}",jsonObject.toString());
        return  jsonObject.toString();
    }

    /**
     * 含位置信息的通用文字识别
     * @param file
     * @return
     */
    public  String general (String file) {
        HashMap<String,String> options = new HashMap<>();
        options.put("language_type", "CHN_ENG");
        // 检测图片朝上
        options.put("detect_direction", "true");
        options.put("vertexes_location", "true");
        options.put("recognize_granularity", "big");
        // 检测语言,默认是不检查
        options.put("detect_language", "true");
        //是否返回识别结果中每一行的置信度
        options.put("probability", "true");
        byte[] bytes = new byte[0];
        try {
            bytes = FileCopyUtils.copyToByteArray(new FileInputStream(file));
        } catch (IOException e) {
            LOGGER.info("AipOcrService | general  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        JSONObject jsonObject =  aipOcrs.general(bytes, options);
        LOGGER.debug("AipOcrService | general  result | jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }

    /**
     * 含位置信息的高精度识别
     * @param file
     * @return
     */
    public  String enhancedGeneral (String file) {
        HashMap<String,String> options = new HashMap<>(6);
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");
        // JSONObject jsonObject = aipOcr.basicAccurateGeneral(file, options);  或者是传url
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | enhancedGeneral  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        //含繁体字版本
        //JSONObject jsonObject = aipOcrs.enhancedGeneral(bytes, options);
//        LOGGER.info("AipOcrService | enhancedGeneral  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.enhancedGeneral(file,options);
//        LOGGER.info("AipOcrService | enhancedGeneral  result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 身份证识别
     * @param file
     * @param side:front正面 ；back背面
     * @return
     */
    public  String idCard (String file,String side) {
        HashMap<String,String> options = new HashMap<>(6);
        options.put("detect_direction", "true");
        //是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能，
        // 默认不开启，即：false。可选值:true-开启；false-不开启
        options.put("detect_risk", "true");
        options.put("id_card_side", side);
        // JSONObject jsonObject = aipOcr.basicAccurateGeneral(file, options);  或者是传url
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | idcard  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        //side:front正面 ；back背面
//        LOGGER.info("AipOcrService | idcard  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.idcard(bytes, side,options);
//        LOGGER.info("AipOcrService | idcard  result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 银行卡识别
     * @param file
     * @return
     */
    public  String bankCard (String file) {
        HashMap<String,String> options = new HashMap<>(6);
        // JSONObject jsonObject = aipOcrJava.basicAccurateGeneral(file, options);  或者是传url
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | bankcard  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        LOGGER.info("AipOcrService | bankcard  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.bankcard(bytes,options);
        LOGGER.info("AipOcrService | bankcard  result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 驾驶证识别
     * @param file
     * @return
     */
    public  String drivingLicense (String file) {
        HashMap<String,String> options = new HashMap<>(6);
        //检查朝上
        options.put("detect_direction", "true");
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | drivingLicense  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        LOGGER.info("AipOcrService | drivingLicense  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.drivingLicense(bytes,options);
        LOGGER.info("AipOcrService | drivingLicense  result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 行驶证识别
     * @param file
     * @param side:front正面 ；back背面
     * @return
     */
    public  String vehicleLicense (String file,String side) {
        HashMap<String,String> options = new HashMap<>(6);
        //不检查朝上
        options.put("detect_direction", "false");
        options.put("accuracy", "normal");
        options.put("vehicle_license_side", side);

        //  normal 使用快速服务，1200ms左右时延；缺省或其它值使用高精度服务，1600ms左右时延
        // JSONObject jsonObject = aipOcr.basicAccurateGeneral(file, options);  或者是传url
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | vehicleLicense  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        LOGGER.info("AipOcrService | vehicleLicense  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.vehicleLicense(bytes,options);
        LOGGER.info("AipOcrService | vehicleLicense  result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 车牌识别
     * @param file
     * @return
     */
    public  String plateLicense (String file) {
        HashMap<String,String> options = new HashMap<>(6);
        options.put("multi_detect", "true");
        //是否检测多张车牌，默认为false，当置为true的时候可以对一张图片内的多张车牌进行识别
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | plateLicense  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        LOGGER.info("AipOcrService | plateLicense  file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.plateLicense(bytes,options);
        LOGGER.info("AipOcrService | plateLicense  result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 营业执照识别
     * @param file
     * @return
     */
    public   String businessLicense (String file) {
        HashMap<String,String> options = new HashMap<>(6);
        options.put("multi_detect", "true");
        byte[] bytes = new byte[0];
        try {
            bytes = Util.readFileByBytes(file);
        } catch (IOException e) {
            LOGGER.info("AipOcrService | businessLicense  file: {} | IOException:{} ",file , e.getMessage());
            e.printStackTrace();
        }
        LOGGER.info("AipOcrService | businessLicense file:{} | options:{} ",file ,options);
        JSONObject jsonObject = aipOcrs.businessLicense(bytes,options);
        LOGGER.info("AipOcrService | businessLicense result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }

    /**
     * 网络图片文字识别, 图片参数为远程url图片
     * @param url
     * @return
     */
    public   String  webImage(String url){
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
//        // 参数为本地图片路径
//        String image = "test.jpg";
//        JSONObject res = aipOcrs.webImage(image, options);
//        System.out.println(res.toString(2));
//
//        // 参数为本地图片二进制数组
//        byte[] file = readImageFile(image);
//        res = aipOcrs.client.webImage(file, options);
//        System.out.println(res.toString(2));


        // 网络图片文字识别, 图片参数为远程url图片
        LOGGER.info("AipOcrService | webImage file:{} | options:{} ",url ,options);
        JSONObject jsonObject = aipOcrs.webImageUrl(url, options);
        LOGGER.info("AipOcrService | webImage result jsonObject:{}",jsonObject.toString());
        return jsonObject.toString();
    }



    public static void main(String[] args) {
        AipOcrService aipOcrService = new AipOcrService();
        //身份证
//        String frontfile = "/Users/duanlikao/Downloads/1侯相科/微信图片_20201027103911.jpg";
//        String frontString = aipOcrService.idCard(frontfile,"front");
//        System.out.println(frontString);
//        System.out.println("#################");
//        String backfile = "/Users/duanlikao/Downloads/1侯相科/微信图片_202010271039111.jpg";
//        String backString = aipOcrService.idCard(backfile,"back");
//        System.out.println(backString);
//        System.out.println("#################");
        String drivingLicensefile = "/Users/duanlikao/Downloads/1侯相科/微信图片_202010271039114.jpg";
        String drivingLicense  = aipOcrService.basicAccurateGeneral(drivingLicensefile);
        System.out.println("#################");
        System.out.println(drivingLicense);
//        System.out.println("#################");
//        String businessLicensefile = "/Users/duanlikao/Downloads/1侯相科/555555.jpeg";
//        String businessLicense  = aipOcrService.drivingLicense(businessLicensefile);
//        System.out.println("#################");
//        System.out.println(businessLicense);
//        System.out.println("#################");
    }
}
